using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Decav.Gatsb.Mobile;
using Decav.Gatsb.Data;
using System.IO;
using Decav.Gatsb.Configuration;
using Decav.Gatsb.Application.Configuration;

namespace Decav.Gatsb.Application.CommandWorkflow
{
    /// <summary>
    /// Posts a <see cref="MobileMessage"/> to Gatsb.
    /// </summary>
	public partial class CreatePostActivity: SequenceActivity
	{
		public CreatePostActivity()
		{
			InitializeComponent();
		}

        /// <summary>
        /// The dependency property that gets or sets the MobileMessage that will be posted to Gatsb.
        /// </summary>
        public static DependencyProperty InputMessageProperty = DependencyProperty.Register(
            "InputMessage", typeof(MobileMessage), typeof(CreatePostActivity));

        /// <summary>
        /// Gets or sets the MobileMessage that will be posted to Gatsb.
        /// </summary>
        [ValidationOption(ValidationOption.Required)]
        public MobileMessage InputMessage
        {
            get { return (MobileMessage)GetValue(InputMessageProperty); }
            set { SetValue(InputMessageProperty, value); }
        }

        /// <summary>
        /// The dependency property that gets or sets the Post to be created.
        /// </summary>
        public static DependencyProperty NewPostProperty = DependencyProperty.Register(
            "NewPost", typeof(Post), typeof(CreatePostActivity));

        /// <summary>
        /// Gets or sets the Post to be created.
        /// </summary
        public Post NewPost
        {
            get { return (Post)GetValue(NewPostProperty); }
            set { SetValue(NewPostProperty, value); }
        }
        

        private void buildPost_ExecuteCode(object sender, EventArgs e)
        {
            if (InputMessage == null)
                throw new ArgumentNullException("InputMessage");

            string body = (InputMessage.Body == null) ? string.Empty : InputMessage.Body.Trim();

            LocationCheckin location = null;
            using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
                location = adapt.GetUserCurrentLocation(GatsbApplication.Current.CurrentUser.Id);

            Post post = null;
            
            if (location.LocationSpecified)
                post = Post.CreatePost(InputMessage.PostTime, body, location.Location.Id);
            else
                post = Post.CreatePost(InputMessage.PostTime, body);

            MmsMessage mediaMessage = InputMessage as MmsMessage;
            if (mediaMessage != null)
            {
                foreach (FileAttachment file in mediaMessage.Attachments)
                {
                    PostAttachment attachment = new PostAttachment();
                    file.Save(Path.Combine(GatsbConfigurationSection.Current.UserUploadedImagesFolder, attachment.Id.ToString()));
                    post.Attachments.Add(attachment);
                }
            }

            using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
                adapt.CreatePost(post);
        }

        private void cleanResponseTextTokens_ExecuteCode(object sender, EventArgs e)
        {
            // Get rid of any "set location" tokens someone accidentally threw in there for us...
            foreach (CommandConfiguration config in GatsbApplicationConfigurationSection.Current.Commands)
            {
                if (config.Name == WorkflowCommandType.SetLocation)
                {
                    foreach (string prefix in config.Prefixes.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (requestLocation.UserResponse.Body.StartsWith(prefix))
                        {
                            requestLocation.UserResponse.Body = requestLocation.UserResponse.Body.Substring(prefix.Length);
                            break;
                        }
                    }

                    break;
                }
            }
        }

        private void notifyNearbyActivity_ExecuteCode(object sender, EventArgs e)
        {
            User[] nearbyUsers = null;
            using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
                nearbyUsers = adapt.GetLocationCurrentVisitors(NewPost.LocationId);

            
            foreach (User nearbyUser in nearbyUsers)
            {
                // don't send to yourself
                if (nearbyUser.Id == GatsbApplication.Current.CurrentUser.Id)
                    continue;

                // Send to anyone in this venue that has permissions to see this.
                if (NewPost.ViewPermissions == PrivacyPermissionLevel.Public ||
                    (NewPost.ViewPermissions == PrivacyPermissionLevel.Friends && nearbyUser.FriendsWithRequester))
                {

                    // TODO: Post Message
                }
            }
        }
        
	}
}
